<template>
  <view class="siteDetail">
    <tabTopBar :title="siteName" :isOpenRightSolt="true" :bgColor="'#132034'">
      <template #right-content>
        <image
          src="/static/select-time.png"
          class="select-time"
          mode=""
          @tap="handleParamsSetting"
        />
      </template>
    </tabTopBar>
    <!-- 头部内容 -->
    <view class="content" v-if="initData">
      <view class="header" v-if="initData.runDays > 0">
        <up-row>
          <up-col span="6">
            <view class="header-left">
              <image src="/static/fault-icon.png" mode="" />
              <text> {{ t("siteDetail.numberOfDaysOfOperation") }} </text>
            </view>
          </up-col>
          <up-col span="6">
            <view class="header-right">
              <text>{{ initData.runDays }}</text>
              <text class="unit">{{ t("siteDetail.day") }}</text>
            </view>
          </up-col>
        </up-row>
      </view>
      <view class="soc-view">
        <chartPage
          :innerRingColor="
            initData.workStatusType == -1 // 故障
              ? '#FA3B3D'
              : initData.workStatusType == 0 // 空闲
              ? '#64B7F6'
              : initData.workStatusType == 1 // 运行
              ? '#34C759'
              : ''
          "
          :fillBgColor="
            initData.workStatusType == -1 // 故障
              ? 'linear-gradient(180deg, #0F1F2F 2%, #FA3B3D 86%)'
              : initData.workStatusType == 0 // 空闲
              ? 'linear-gradient(180deg, #0F1F2F 2%, #64B7F6 86%)'
              : initData.workStatusType == 1 // 运行
              ? 'linear-gradient(180deg, #0F1F2F 2%, #34C759 86%)'
              : ''
          "
          :batteryPercentage="initData.soc"
        />
        <view class="operationalStatus">
          <view v-if="initData.workStatus">
            {{ initData.workStatus }}
          </view>
        </view>
      </view>

      <up-row gutter="10">
        <up-col span="6">
          <view class="equipment">
            <text class="name">{{ t("siteDetail.totalNumberOfDevices") }}</text>
            <text>{{ initData.deviceNumber }}</text>
          </view>
        </up-col>
        <up-col span="6">
          <view class="equipment equipment-right">
            <text class="name">{{ t("siteDetail.workingMode") }}</text>
            <text>{{ initData.workMode }}</text>
          </view>
        </up-col>
      </up-row>

      <view class="electricity-detail">
        <up-row :align="'top'">
          <up-col span="3">
            <view class="electricity-detail-item">
              <view class="number">
                {{ powerUnit(initData.systemActivePower, 0) }}
              </view>
              <image class="img" src="/static/dividingLine-icon.png" mode="" />
              <view class="electricity-type">
                {{ t("siteDetail.realTimePower") }}
              </view>
              <view class="unit">
                ({{ powerUnit(initData.systemActivePower, 1) }})
              </view>
            </view>
          </up-col>
          <up-col span="3">
            <view class="electricity-detail-item">
              <view class="electricity-detail-item">
                <view class="number">{{ initData.efficiency }}</view>
                <image
                  class="img"
                  src="/static/dividingLine-icon.png"
                  mode=""
                />
                <view class="electricity-type">
                  {{ t("siteDetail.siteEfficiency") }}
                </view>
                <view class="unit"> (%) </view>
              </view>
            </view>
          </up-col>
          <up-col span="3">
            <view class="electricity-detail-item">
              <view class="electricity-detail-item">
                <view class="number">
                  {{ chargeUnit(initData.totalCharge, 0) }}
                </view>
                <image
                  class="img"
                  src="/static/dividingLine-icon.png"
                  mode=""
                />
                <view class="electricity-type">
                  {{ t("siteDetail.totalCharge") }}
                </view>
                <view class="unit">
                  ({{ chargeUnit(initData.totalCharge, 1) }})
                </view>
              </view>
            </view>
          </up-col>
          <up-col span="3">
            <view class="electricity-detail-item">
              <view class="electricity-detail-item">
                <view class="number">
                  {{ chargeUnit(initData.totalDischarge, 0) }}
                </view>
                <image
                  class="img"
                  src="/static/dividingLine-icon.png"
                  mode=""
                />
                <view class="electricity-type">
                  {{ t("siteDetail.totalDischarge") }}
                </view>
                <view class="unit">
                  ({{ chargeUnit(initData.totalDischarge, 1) }})
                </view>
              </view>
            </view>
          </up-col>
        </up-row>
      </view>
      <!--  -->
    </view>

    <!-- 站点拓扑 -->

    <view class="page-item">
      <siteTopology :siteTopologyData="siteTopologyData" />
      <!-- <siteTopologyTo :siteTopologyData="siteTopologyData" /> -->
    </view>

    <!-- 故障列表 -->
    <view class="page-item">
      <listOfFaults
        :faultDataList="faultDataList"
        :equipmentDataList="equipmentDataList"
        @equipmentFaultDataList="getEquipmentFaultList"
        @goDeviceDetails="goDeviceDetails"
        ref="listOfFaultsRef"
        @handlegoEquipmentDetail="handlegoEquipmentDetail"
      />
    </view>
    <!-- 站点收益 -->
    <view class="page-item" v-show="isShowtypeProfit">
      <siteAnalyse
        @setDateType="siteEarnings"
        ref="siteAnalyseRef"
        :earningsStatisticsData="earningsStatisticsData"
        :earningsStatisticschartOption="earningsStatisticschartOption"
      />
    </view>

    <!-- 功率分析 -->
    <view class="page-item">
      <powerAnalyse
        @handleTime="handlePowerAnalysis"
        ref="powerAnalyseRefs"
        :powerChart="powerChart"
      />
    </view>
    <!-- 充分分析 -->
    <!-- v-show="Object.keys(suffChart).length !== 0" -->
    <view class="page-item" v-show="Object.keys(suffChart).length !== 0">
      <sufficiencyAnalyse :suffChart="suffChart" />
    </view>
    <!-- 故障告警分析 -->
    <!-- v-show="Object.keys(faultChart).length !== 0" -->
    <!-- <view class="page-item" v-show="Object.keys(faultChart).length !== 0">
      <faultAnalyse :faultChart="faultChart" />
    </view> -->
  </view>
</template>

<script setup>
import { ref, nextTick, computed, watch } from "vue";
import siteTopology from "./components/siteTopology.vue";
// import siteTopologyTo from "./components/siteTopology.vue";
import listOfFaults from "./components/listOfFaults.vue";
import { onLoad, onPullDownRefresh } from "@dcloudio/uni-app";
import apis from "@/apis/index.js";
import {
  powerUnit,
  chargeUnit,
  calculateAverage,
  formatPowerUnitOfUnit,
  formatMoney,
  formatMoneyOfUnit,
  formatElectricityOfUnit,
} from "@/utils/utils";
const siteId = ref();
const initData = ref({});
const siteAnalyseRef = ref(null);
const earningsStatisticsData = ref({});
const earningsStatisticschartOption = ref({});
const powerAnalyseRefs = ref(null);
const powerChart = ref({});
const suffChart = ref({});
const faultChart = ref({});

const faultDataList = ref([]);
const equipmentDataList = ref([]);
const listOfFaultsRef = ref(null);
const siteTopologyData = ref({});
const isShowSuff = ref(false);
import { useI18n } from "vue-i18n";
const { t } = useI18n();

const isShowtypeProfit = ref(false);

const siteName = ref();
onLoad((options) => {
  siteName.value = options.siteName;
  siteId.value = options.siteId;
  init();
});

onPullDownRefresh(() => {
  // 下拉刷新时重新获取数据;
  init(() => {
    // 数据获取完成后停止下拉刷新动画
    uni.stopPullDownRefresh();
  });
});

const init = (callback) => {
  let params = {
    siteId: siteId.value,
  };
  apis.getSiteDetails(params).then((res) => {
    if (res.code == 200) {
      initData.value = res.data;
      console.log("基础数据", initData.value);
    }
  });

  // 站点谱图
  topology();
  // // 设备列表与故障列表
  getEquipmentFaultList();
  // 站点收益
  siteEarnings();
  // 功率分析
  handlePowerAnalysis();
  // 充放分析
  chargeAndDischargeAnalysis();
  // 告警分析
  chartOfAlar();

  nextTick(() => {
    if (callback) {
      callback();
    }
  });
};

const handleParamsSetting = () => {
  uni.navigateTo({
    url: `/pages/site-parameter-settings/site-parameter-settings?name=${siteName.value}&id=${siteId.value}`,
  });
};
const goDeviceDetails = () => {
  let type = listOfFaultsRef.value.getListType();
  let name = "";

  uni.navigateTo({
    url: `/pages/deviceDetails/deviceDetails?echartsType=${type}&siteId=${siteId.value}&siteName=${siteName.value}`,
  });
};

// 年收益

const annualEarnings = () => {
  let params = {
    dateType: 3,
    siteId: siteId.value,
  };
  apis.earningsStatistics(params).then((res) => {
    if (res.code == 200) {
      isShowtypeProfit.value = res.data.typeProfit == 0 ? false : true;
    }
  });
};

// 站点收益
const siteEarnings = () => {
  nextTick(() => {
    let params = {
      dateType: siteAnalyseRef.value.handleDateType(),
      siteId: siteId.value,
    };
    annualEarnings();
    apis.earningsStatistics(params).then((res) => {
      if (res.code == 200) {
        earningsStatisticsData.value = res.data;
      }
    });
    apis.yieldCurve(params).then((res) => {
      if (res.code == 200) {
        let date = [];
        let profit = [];
        let profitArr = [];
        res.data.forEach((item) => {
          profitArr.push(Number(item.profit));
        });
        const pinjun = calculateAverage(profitArr);
        const unit = formatMoney(pinjun).templete;
        res.data.forEach((item) => {
          date.push(item.date);
          profit.push(formatMoneyOfUnit(item.profit, unit));
        });
        if (profit && profit.length > 0) {
          // 计算 Y 轴最大数值的字符长度
          const maxValue = Math.max(...profit);
          const maxLength = maxValue.toString().length;
          // 根据字符长度动态调整 grid 的 left 值
          const baseLeft = -2; // 基础 left 百分比
          const additionalLeft = maxLength * 2; // 每个字符增加 2% 的 left 值
          const newLeft = Math.min(baseLeft + additionalLeft, 30); // 最大不超过 30%
          const chart = {
            title: {
              text: t(unit),
              top: 10,
              left: 16,
              textStyle: {
                fontSize: 10, // 标题字体大小
                color: "#6E7180", // 标题字体颜色，这里设置为红色
              },
            },
            xAxis: {
              type: "category",
              boundaryGap: false, // 确保折线图的起点和终点与坐标轴的两端对齐
              data: date,
              axisTick: {
                lineStyle: {
                  type: "dashed", // 设置 x 轴刻度线为虚线
                },
              },
            },
            yAxis: {
              type: "value",
              axisLabel: {
                show: true,
                color: "#6e7180",
              },
              axisTick: {
                lineStyle: {
                  type: "dashed", // 设置 y 轴刻度线为虚线
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: "#6e7180", // 修改 x 轴网格横线颜色为红色
                  type: "dashed", // 设置 y 轴刻度线为虚线
                },
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: "#6e7180",
                },
              },
            },
            series: [
              {
                data: profit,
                type: "line",
                smooth: true,
                lineStyle: {
                  color: "#64B7F6", // 修改线条颜色为红色
                },
                itemStyle: {
                  color: "#FFFFFF",
                  border: "1rpx solid #64B7F6",
                },
                label: {
                  show: true,
                  position: "top",
                  formatter: "{c}",
                  color: "#FFFFFF",
                },
                areaStyle: {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "#1F3550", // 渐变起始颜色
                      },
                      {
                        offset: 1,
                        color: "#132136", // 渐变结束颜色
                      },
                    ],
                  },
                },
              },
            ],
            tooltip: {
              show: true,
              trigger: "axis",
              position: function (point, params, dom, rect, size) {
                // point: 鼠标位置，格式为 [x, y]
                // params: 提示框所对应的数据项
                // dom: 提示框的 DOM 节点
                // rect: 图表的 DOM 节点的矩形框信息
                // size: 提示框的大小信息，格式为 {contentSize: [width, height], viewSize: [width, height]}
                let x = point[0];
                let y = point[1];
                let viewWidth = size.viewSize[0];
                let viewHeight = size.viewSize[1];
                let boxWidth = size.contentSize[0];
                let boxHeight = size.contentSize[1];

                // 确保 tooltip 在页面内完全显示
                if (x + boxWidth > viewWidth) {
                  x = viewWidth - boxWidth;
                }
                if (y - boxHeight < 0) {
                  y = boxHeight;
                }

                return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
              },
              backgroundColor: "#fff", // 设置背景颜色为白色
              borderColor: "#ccc", // 设置边框颜色
              borderWidth: 1, // 设置边框宽度
              extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
              formatter: function (params) {
                let xAxisValue = params[0].axisValue; // 获取 x 轴时间
                let tooltipStr = `${xAxisValue}\n`; // 将 x 轴时间添加到最上面一行
                params.forEach(function (param) {
                  tooltipStr += `${param.value + t(unit)} \n`;
                });
                return tooltipStr.replace(/\n$/, ""); // 移除末尾 <br/>
              },
            },
            grid: {
              top: "12%", // 上边距
              right: "6%", // 右边距
              bottom: "1%", // 下边距
              left: newLeft, // 左边距
              containLabel: true, // 是否包含坐标轴的标签
            },
            dataZoom: [
              {
                type: "inside", // 内部缩放
                xAxisIndex: 0,
                start: 0,
                end: (7 / date.length) * 100, // 默认展示前 6 个数据
                zoomOnMouseWheel: false, // 禁止鼠标滚轮缩放
                moveOnMouseMove: true, // 允许鼠标拖动
                moveOnMouseWheel: false, // 禁止鼠标滚轮移动
              },
            ],
          };
          earningsStatisticschartOption.value = chart;
        }
      }
    });
  });
};
// 功率分析
const handlePowerAnalysis = () => {
  nextTick(() => {
    let params = {
      currTime: powerAnalyseRefs.value.getTimeJson(),
      siteId: siteId.value,
    };
    apis.getPowerAnalysis(params).then((res) => {
      console.log("res功率分析", res);
      if (res.code == 200) {
        let currTimeArr = []; //时间
        let gridActivePowerTest = []; // 电网功率
        let loadActivePowerTest = []; //负载功率
        let systemActivePowerTest = []; // 储能功率
        res.data.forEach((item) => {
          gridActivePowerTest.push(item.gridActivePower);
          loadActivePowerTest.push(item.loadActivePower);
          systemActivePowerTest.push(item.systemActivePower);
        });

        let arr = calculateAverage(
          ...gridActivePowerTest,
          ...loadActivePowerTest,
          ...systemActivePowerTest
        );
        let unit = powerUnit(arr, 1);
        let gridActivePower = []; // 电网功率
        let loadActivePower = []; //负载功率
        let systemActivePower = []; // 储能功率
        res.data.forEach((item) => {
          currTimeArr.push(item.currTime);
          gridActivePower.push(
            formatPowerUnitOfUnit(item.gridActivePower, unit)
          );
          loadActivePower.push(
            formatPowerUnitOfUnit(item.loadActivePower, unit)
          );
          systemActivePower.push(
            formatPowerUnitOfUnit(item.systemActivePower, unit)
          );
        });
        // 计算 Y 轴最大数值的字符长度
        const maxValue = Math.max(
          ...gridActivePower,
          ...loadActivePower,
          ...systemActivePower
        );
        const yAxisMax = maxValue <= 125 ? 125 : Math.ceil(maxValue * 1.1);
        if (
          gridActivePower.length > 0 &&
          loadActivePower.length > 0 &&
          systemActivePower.length > 0
        ) {
          const maxLength = maxValue.toString().length;
          // 根据字符长度动态调整 grid 的 left 值
          const baseLeft = -2; // 基础 left 百分比
          const additionalLeft = maxLength * 2; // 每个字符增加 2% 的 left 值
          const newLeft = Math.min(baseLeft + additionalLeft, 30); // 最大不超过 30%
          const powerOption = {
            title: {
              text: unit,
              top: 10,
              left: 16,
              textStyle: {
                fontSize: 10, // 标题字体大小
                color: "#6E7180", // 标题字体颜色，这里设置为红色
              },
            },
            xAxis: {
              type: "category",
              data: currTimeArr,
              axisTick: {
                lineStyle: {
                  type: "dashed", // 设置 x 轴刻度线为虚线
                },
              },
            },
            yAxis: {
              type: "value",
              max: yAxisMax,
              axisLabel: {
                show: true,
                color: "#6e7180",
              },
              axisTick: {
                lineStyle: {
                  type: "dashed", // 设置 y 轴刻度线为虚线
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  type: "dashed", // 设置 y 轴网格线为虚线
                  color: "#6e7180", // 修改 x 轴网格横线颜色为红色
                },
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: "#6e7180",
                },
              },
            },

            tooltip: {
              show: true,
              trigger: "axis",
              position: function (point, params, dom, rect, size) {
                // point: 鼠标位置，格式为 [x, y]
                // params: 提示框所对应的数据项
                // dom: 提示框的 DOM 节点
                // rect: 图表的 DOM 节点的矩形框信息
                // size: 提示框的大小信息，格式为 {contentSize: [width, height], viewSize: [width, height]}
                let x = point[0];
                let y = point[1];
                let viewWidth = size.viewSize[0];
                let viewHeight = size.viewSize[1];
                let boxWidth = size.contentSize[0];
                let boxHeight = size.contentSize[1];

                // 确保 tooltip 在页面内完全显示
                if (x + boxWidth > viewWidth) {
                  x = viewWidth - boxWidth;
                }
                if (y - boxHeight < 0) {
                  y = boxHeight;
                }

                return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
              },
              backgroundColor: "#fff", // 设置背景颜色为白色
              borderColor: "#ccc", // 设置边框颜色
              borderWidth: 1, // 设置边框宽度
              extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
              formatter: function (params) {
                let xAxisValue = params[0].axisValue; // 获取 x 轴时间
                let tooltipStr = `${xAxisValue}\n`; // 将 x 轴时间添加到最上面一行
                params.forEach(function (param) {
                  tooltipStr += `${param.seriesName}: ${param.value + unit} \n`;
                });
                return tooltipStr.replace(/\n$/, ""); // 移除末尾 <br/>
              },
            },
            legend: {
              icon: "rect",
              right: "5%",
              itemWidth: 12,
              itemHeight: 8,
              itemStyle: {
                borderRadius: 20, // 调整后的圆角值
                borderWidth: 0, // 设置边框宽度为0
              },
              textStyle: {
                // 设置图例文字的大小
                fontSize: 10,
                // 设置图例文字的颜色
                color: "#6e7180",
              },
              data: [
                {
                  name: t("siteDetail.energyStoragePower"),
                  icon: "rect",
                  itemStyle: {
                    color: "#64B7F6", // 对应储能功率折线图线条颜色
                  },
                },
                {
                  name: t("siteDetail.gridPower"),
                  icon: "rect",
                  itemStyle: {
                    color: "#805EDA", // 对应电网功率折线图线条颜色
                  },
                },
                {
                  name: t("siteDetail.loadPower"),
                  icon: "rect",
                  itemStyle: {
                    color: "#FFA200", //对应负载功率折线图线条颜色
                  },
                },
              ],
            },
            grid: {
              top: "12%", // 上边距
              right: "6%", // 右边距
              bottom: "1%", // 下边距
              left: newLeft, // 左边距
              containLabel: true, // 是否包含坐标轴的标签
            },
            series: [
              {
                name: t("siteDetail.energyStoragePower"),
                symbol: "none", // 取消小圆点
                data: systemActivePower,
                type: "line",
                lineStyle: {
                  color: "#64B7F6", // 修改线条颜色为红色
                },
                areaStyle: {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "rgba(39, 46, 78, 0.9)", // 渐变起始颜色，降低透明度
                      },
                      {
                        offset: 1,
                        color: "rgba(31, 40, 68, 0.9)", // 渐变结束颜色，降低透明度
                      },
                    ],
                  },
                },
              },
              {
                name: t("siteDetail.gridPower"),
                symbol: "none", // 取消小圆点
                data: gridActivePower,
                type: "line",
                lineStyle: {
                  color: "#805EDA", // 修改线条颜色为红色
                },
                areaStyle: {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "rgba(55, 55, 67, 0.9)", // 渐变起始颜色，降低透明度
                      },
                      {
                        offset: 1,
                        color: "rgba(38, 43, 57, 0.9)", // 渐变结束颜色，降低透明度
                      },
                    ],
                  },
                },
              },
              {
                name: t("siteDetail.loadPower"),
                symbol: "none", // 取消小圆点
                data: loadActivePower,
                type: "line",
                // smooth: true,
                lineStyle: {
                  color: "#FFA200", // 修改线条颜色为红色
                },
                areaStyle: {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "rgba(47, 57, 77, 0.9)", // 渐变起始颜色，降低透明度
                      },
                      {
                        offset: 1,
                        color: "rgba(33, 46, 65, 0.9)", // 渐变结束颜色，降低透明度
                      },
                    ],
                  },
                },
              },
            ],
            dataZoom: [],
          };
          powerChart.value = powerOption;
        } else {
          powerChart.value = {};
        }
        console.log("powerChart.value", powerChart.value);
      }
    });
  });
};
// 充放分析
// const isShowSuff = computed(() => {
//   return Object.keys(suffChart.value).length !== 0;
// });

const isShowsiteAnalyse = computed(() => {
  return Object.keys(earningsStatisticschartOption.value).length !== 0;
});

const chargeAndDischargeAnalysis = () => {
  let params = {
    siteId: siteId.value,
  };
  apis.getChargeAnalysis(params).then((res) => {
    console.log("充放分析", res);
    if (res.code == 200) {
      let createDateArr = []; // 时间

      let chargeArr = []; // 充电量
      let dischargeArr = []; // 放电量
      let efficiencyArr = []; // 效率

      let chargeArrTest = []; // 充电量
      let dischargeArrTest = []; // 放电量

      res.data.forEach((item, index) => {
        chargeArrTest.push(Number(item.charge));
        dischargeArrTest.push(Number(item.discharge));
      });

      const pinjin = calculateAverage(...chargeArrTest, ...dischargeArrTest);
      const unit = chargeUnit(pinjin, 1);

      res.data.forEach((item, index) => {
        chargeArr.push(formatElectricityOfUnit(item.charge, unit));
        createDateArr.push(item.createDate);
        dischargeArr.push(formatElectricityOfUnit(item.discharge, unit));
        if (item.efficiency >= 70 && item.efficiency <= 100) {
          efficiencyArr.push(item.efficiency);
        } else {
          efficiencyArr.push(null); // 过滤掉小于 70% 和大于 100% 的数据
        }
      });
      // 计算 Y 轴最大数值的字符长度
      const maxValue = Math.max(
        ...chargeArr,
        ...dischargeArr,
        ...efficiencyArr
      );
      let maxVal = Math.max(...chargeArr, ...dischargeArr);
      const yAxisMax = maxVal <= 50 ? 50 : Math.ceil(maxVal * 1.1);

      if (
        chargeArr.length > 0 &&
        dischargeArr.length > 0 &&
        efficiencyArr.length > 0
      ) {
        const maxLength = maxValue.toString().length;
        // 根据字符长度动态调整 grid 的 left 值
        const baseLeft = -2; // 基础 left 百分比
        const additionalLeft = maxLength * 2; // 每个字符增加 2% 的 left 值
        const newLeft = Math.min(baseLeft + additionalLeft, 30); // 最大不超过 30%
        const highestEfficiency = Math.max(...efficiencyArr);
        console.log("highestEfficiency??????", highestEfficiency);

        const chartOfSuff = {
          title: [
            {
              text: unit,
              top: 10,
              left: 16,
              textStyle: {
                fontSize: 10, // 标题字体大小
                color: "#6E7180", // 标题字体颜色，这里设置为红色
              },
            },
            {
              text: "%",
              top: 10,
              right: 16,
              textStyle: {
                fontSize: 10, // 标题字体大小
                color: "#6E7180", // 标题字体颜色，这里设置为红色
              },
            },
          ],
          xAxis: {
            type: "category",
            data: createDateArr,
          },
          yAxis: [
            {
              type: "value",
              max: yAxisMax,
              axisLabel: {
                show: true,
                color: "#6e7180",
              },
              axisTick: {
                lineStyle: {
                  type: "dashed", // 设置 y 轴刻度线为虚线
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  type: "dashed", // 设置 y 轴网格线为虚线
                  color: "#6e7180", // 修改 x 轴网格横线颜色为红色
                },
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: "#6e7180",
                },
              },
            },
            {
              type: "value",
              position: "right", // 将该纵轴放置在右侧
              nameTextStyle: {
                color: "#6e7180", // 纵轴名称文字颜色
              },
              axisLabel: {
                show: true,
                color: "#6e7180",
                formatter: "{value}", // 显示百分比格式
              },
              splitLine: {
                show: false, // 不显示网格线
              },
              splitLine: {
                show: false, // 不显示网格线
              },
              axisLine: {
                show: false,
                lineStyle: {
                  color: "#6e7180",
                },
              },
              // min: 0, // 最小值
              // max: highestEfficiency > 100 ? highestEfficiency + 30 : 100, // 最大值
            },
          ],

          tooltip: {
            show: true,
            trigger: "axis",
            position: function (point, params, dom, rect, size) {
              // point: 鼠标位置，格式为 [x, y]
              // params: 提示框所对应的数据项
              // dom: 提示框的 DOM 节点
              // rect: 图表的 DOM 节点的矩形框信息
              // size: 提示框的大小信息，格式为 {contentSize: [width, height], viewSize: [width, height]}
              let x = point[0];
              let y = point[1];
              let viewWidth = size.viewSize[0];
              let viewHeight = size.viewSize[1];
              let boxWidth = size.contentSize[0];
              let boxHeight = size.contentSize[1];

              // 确保 tooltip 在页面内完全显示
              if (x + boxWidth > viewWidth) {
                x = viewWidth - boxWidth;
              }
              if (y - boxHeight < 0) {
                y = boxHeight;
              }

              return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
            },
            backgroundColor: "#fff", // 设置背景颜色为白色
            borderColor: "#ccc", // 设置边框颜色
            borderWidth: 1, // 设置边框宽度
            extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
            formatter: function (params) {
              let xAxisValue = params[0].axisValue; // 获取 x 轴时间
              let tooltipStr = `${xAxisValue}\n`; // 将 x 轴时间添加到最上面一行
              params.forEach(function (param) {
                if (param.seriesName === t("siteDetail.efficiency")) {
                  // 确保效率数据后面带有 % 单位
                  if (param.value < 70 || param.value > 100 || !param.value) {
                    tooltipStr += `${param.seriesName}: - \n`;
                  } else {
                    tooltipStr += `${param.seriesName}: ${param.value}% \n`;
                  }
                } else {
                  tooltipStr += `${param.seriesName}: ${param.value} ${unit} \n`;
                }
              });

              return tooltipStr.replace(/\n$/, ""); // 移除末尾 <br/>
            },
          },
          legend: {
            icon: "rect",
            right: "5%",
            itemWidth: 12,
            itemHeight: 8,
            itemStyle: {
              borderRadius: 20, // 调整后的圆角值
              borderWidth: 0, // 设置边框宽度为0
            },
            textStyle: {
              // 设置图例文字的大小
              fontSize: 10,
              // 设置图例文字的颜色
              color: "#6e7180",
            },
            data: [
              {
                name: t("siteDetail.chargeCapacity"),
                icon: "rect",
                itemStyle: {
                  color: "#8BDACC", // 对应充电量折线图线条颜色
                },
              },
              {
                name: t("siteDetail.dischargeAmount"),
                icon: "rect",
                itemStyle: {
                  color: "#5EABE6", // 对应放电量折线图线条颜色
                },
              },
              {
                name: t("siteDetail.efficiency"),
                icon: "rect",
                itemStyle: {
                  color: "#9670F9", //对应效率折线图线条颜色
                },
              },
            ],
          },
          grid: {
            top: "12%", // 上边距
            right: "6%", // 右边距
            bottom: "1%", // 下边距
            left: newLeft, // 左边距
            containLabel: true, // 是否包含坐标轴的标签
          },

          series: [
            {
              name: t("siteDetail.chargeCapacity"),
              type: "bar", // 修改为柱状图
              data: chargeArr,
              yAxisIndex: 0, // 使用第一个 y 轴（左侧）
              itemStyle: {
                color: {
                  type: "linear",
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: "#192E3D", // 渐变起始颜色，降低透明度
                    },
                    {
                      offset: 1,
                      color: "#8BDACC", // 渐变结束颜色，降低透明度
                    },
                  ],
                },
                borderRadius: [20, 20, 20, 20], // 设置上下圆角
              },
              barWidth: 10,
            },
            {
              name: t("siteDetail.dischargeAmount"),
              type: "bar", // 修改为柱状图
              data: dischargeArr,
              yAxisIndex: 0, // 使用第一个 y 轴（左侧）
              itemStyle: {
                color: {
                  type: "linear",
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: "#2B4C65", // 渐变起始颜色，降低透明度
                    },
                    {
                      offset: 1,
                      color: "#5EABE6", // 渐变结束颜色，降低透明度
                    },
                  ],
                },
                borderRadius: [20, 20, 20, 20], // 设置上下圆角
              },
              barWidth: 10,
            },
            {
              name: t("siteDetail.efficiency"),
              smooth: true,

              symbol: "circle", // 在曲线上添加小点
              symbolSize: 6, // 小点的大小
              itemStyle: {
                color: "#9670F9", // 小点颜色
              },
              data: efficiencyArr,
              yAxisIndex: 1, // 使用第二个 y 轴（右侧）
              type: "line",
              lineStyle: {
                color: "#9670F9", // 修改线条颜色为红色
              },
            },
          ],
          dataZoom: [
            // {
            //   type: "inside", // 内部缩放
            //   xAxisIndex: 0,
            //   start: 0,
            //   end: (7 / createDateArr.length) * 100, // 默认展示前 6 个数据
            //   zoomOnMouseWheel: false, // 禁止鼠标滚轮缩放
            //   moveOnMouseMove: true, // 允许鼠标拖动
            //   moveOnMouseWheel: false, // 禁止鼠标滚轮移动
            // },
          ],
        };
        // suffChart
        // chartOfSuff
        suffChart.value = chartOfSuff;
        console.log("suffChart.value", suffChart.value);
      } else {
        suffChart.value = {};
      }
    }
  });
};

// 告警分析

const chartOfAlar = () => {
  let params = {
    siteId: siteId.value,
  };
  apis.getEvaluate(params).then((res) => {
    if (res.code == 200) {
      let arr = [];
      res.data.forEach((item) => {
        let obj = {
          value: item.count,
          name: item.module,
          percent: item.percentage,
          sum: item.sum,
        };
        arr.push(obj);
      });
      if (arr.length > 0) {
        const alarChart = {
          tooltip: {
            show: true,
            trigger: "axis",
            position: function (point, params, dom, rect, size) {
              // point: 鼠标位置，格式为 [x, y]
              // params: 提示框所对应的数据项
              // dom: 提示框的 DOM 节点
              // rect: 图表的 DOM 节点的矩形框信息
              // size: 提示框的大小信息，格式为 {contentSize: [width, height], viewSize: [width, height]}
              let x = point[0];
              let y = point[1];
              let viewWidth = size.viewSize[0];
              let viewHeight = size.viewSize[1];
              let boxWidth = size.contentSize[0];
              let boxHeight = size.contentSize[1];

              // 确保 tooltip 在页面内完全显示
              if (x + boxWidth > viewWidth) {
                x = viewWidth - boxWidth;
              }
              if (y - boxHeight < 0) {
                y = boxHeight;
              }

              return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
            },
            backgroundColor: "#fff", // 设置背景颜色为白色
            borderColor: "#ccc", // 设置边框颜色
            borderWidth: 1, // 设置边框宽度
            extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
            trigger: "item",
            formatter: "{b} : {c} ({d}%)",
          },

          series: [
            {
              name: t("siteDetail.totalNumberOfSiteAlarms"),
              type: "pie",
              radius: ["40%", "50%"], // 环形图内外半径
              center: ["50%", "50%"],
              data: arr,
              label: {
                show: true,
                color: "#ffffff",
                formatter: function (params) {
                  // 在引导线指示的内容中间加间隔
                  return (
                    params.name +
                    "\n" +
                    params.value +
                    "\n" +
                    params.percent +
                    "%"
                  );
                },
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.5)",
                },
              },
            },
          ],
          graphic: [
            // 上方元素
            {
              type: "text",
              left: "center",
              top: "45%",
              style: {
                text: arr[0].sum,
                fontSize: 30,
                fontWeight: "bold",
                fill: "#fff",
              },
            },
            // 下方元素
            {
              type: "text",
              left: "center",
              top: "55%",
              style: {
                text: t("siteDetail.totalNumberOfSiteAlarms"),
                fontSize: 14,
                fontWeight: "bold",
                fill: "#fff",
              },
            },
          ],
        };
        faultChart.value = alarChart;
      } else {
        faultChart.value = {};
      }
      console.log("faultChart.value ", faultChart.value);
    }
  });
};

// 站点谱图
const topology = () => {
  let params = {
    siteId: siteId.value,
  };
  apis.getSiteTopology(params).then((res) => {
    console.log("站点谱图", res);
    if (res.code == 200) {
      siteTopologyData.value = res.data;
    }
  });
};

// 设备列表与故障列表
const getEquipmentFaultList = () => {
  nextTick(() => {
    let type = listOfFaultsRef.value.getListType();
    if (type == 1) {
      let params = {
        siteId: siteId.value,
        current: 1,
        limit: 10,
      };
      apis.getDeviceList(params).then((res) => {
        if (res.code == 200) {
          equipmentDataList.value = res.data;
          console.log("设备列表", equipmentDataList.value);
        }
      });
    } else if (type == 2) {
      let params = {
        siteId: siteId.value,
        current: 1,
        limit: 10,
      };
      apis.getAlarmList(params).then((res) => {
        if (res.code == 200) {
          faultDataList.value = res.data.records;
          console.log("故障列表", faultDataList.value);
        }
      });
    }
  });
};

const handlegoEquipmentDetail = (item) => {
  uni.navigateTo({
    url: `/pages/equipmentDetail/equipmentDetail?params=${item}&siteName=${siteName.value}`,
  });
};
</script>

<style lang="scss" scoped>
.siteDetail {
  width: 100%;
  padding-bottom: 30rpx;
  box-sizing: border-box;
}

.select-time {
  width: 28rpx;
  height: 32rpx;
}

.content {
  width: 100%;
  padding: 24rpx 32rpx 62rpx 32rpx;
  box-sizing: border-box;
  background: linear-gradient(180deg, #08121e 58%, #132034 100%);
  border-bottom-right-radius: 30rpx;
  border-bottom-left-radius: 30rpx;

  .soc-view {
    width: 100%;
    position: relative;

    .operationalStatus {
      position: absolute;
      top: 30rpx;
      left: 520rpx;
      font-family: PingFang SC Regular;
      font-size: 24rpx;
      font-weight: normal;
      color: #bfbfbf;
      margin-bottom: 20rpx;
    }
  }

  .header {
    width: 100%;
    padding: 30rpx 32rpx;
    box-sizing: border-box;
    background: #132034;
    border-radius: 10rpx;
  }

  .header-left,
  .header-right {
    width: 100%;
    display: flex;
    align-items: center;
  }

  .header-left {
    justify-content: flex-start;

    image {
      width: 28rpx;
      height: 28rpx;
      margin-right: 12rpx;
    }

    text {
      font-family: PingFang SC Regular;
      font-size: 28rpx;
      font-weight: normal;
      color: #acb1b8;
    }
  }

  .header-right {
    justify-content: flex-end;

    text {
      font-family: D-DIN;
      font-size: 40rpx;
      font-weight: bold;
      color: #ffffff;
    }

    .unit {
      font-family: PingFang SC Regular;
      font-size: 28rpx;
      font-weight: normal;
      color: #acb1b8;
      margin-left: 12rpx;
    }
  }

  .equipment {
    margin-top: 20rpx;
    width: 100%;
    padding: 30rpx 32rpx;
    box-sizing: border-box;
    background-color: #132034;
    border-radius: 10rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    text {
      font-family: D-DIN;
      font-size: 40rpx;
      font-weight: bold;
      color: #ffffff;
    }

    .name {
      font-family: PingFang SC Regular;
      font-size: 28rpx;
      font-weight: normal;
      color: #868d97;
      position: relative;
    }

    .name::after {
      content: "";
      position: absolute;
      width: 12rpx;
      height: 12rpx;
      border-radius: 50%;
      background: #64b7f6;
      top: 50%;
      transform: translateY(-50%);
      left: -20rpx;
    }
  }

  .equipment-right {
    float: right;

    .name::after {
      content: "";
      background: #805eda;
    }
  }

  .electricity-detail {
    width: 100%;
    margin-top: 58rpx;

    .electricity-detail-item {
      width: 100%;
      text-align: center;

      .number {
        font-family: D-DIN;
        font-size: 40rpx;
        font-weight: bold;
        text-align: center;
        font-variation-settings: "opsz" auto;
        color: #eeeeee;
        width: 100%;
        white-space: nowrap;
        /* 禁止文本换行 */
        overflow: hidden;
        /* 超出部分隐藏 */
        text-overflow: ellipsis;
        /* 超出部分显示省略号 */
      }

      .img {
        width: 60rpx;
        height: 3rpx;
        margin: 20rpx auto;
      }

      .electricity-type {
        font-family: Alibaba PuHuiTi 3;
        font-size: 24rpx;
        font-weight: normal;
        text-align: center;
        font-variation-settings: "opsz" auto;
        color: #a0a2a1;
      }

      .unit {
        font-family: Alibaba PuHuiTi 3;
        font-size: 24rpx;
        font-weight: normal;
        text-align: center;
        font-variation-settings: "opsz" auto;
        color: #a0a2a1;
      }
    }
  }
}

.page-item {
  width: 100%;
  padding: 0 32rpx;
  box-sizing: border-box;
  margin-top: 24rpx;
}

.analyse-item {
  width: 100%;
  padding: 0 32rpx;
  box-sizing: border-box;
  margin-top: 24rpx;
}
</style>
